package com.oracle.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.oracle.common.PageResult;
import com.oracle.mapper.GlyMapper;
import com.oracle.pojo.Gly;
import com.oracle.pojo.GlyExample;
import com.oracle.service.GlyService;
import com.oracle.vo.GlyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class GlyServiceImpl implements GlyService {
    @Autowired(required = false)
    private GlyMapper glyMapper;

    @Override
    public List<Gly> findList(){
        List<Gly> glys = glyMapper.selectByExample(null);

        return glys;
    }

    @Override
    public Gly login(String loginName, String password)
    {
        Gly gly = null;
        GlyExample example = new GlyExample();
        GlyExample.Criteria criteria = example.createCriteria();
        criteria.andGlyUsernameEqualTo(loginName);
        criteria.andGlyPasswordEqualTo(password);

        List<Gly> glies =glyMapper.selectByExample(example);

        if(glies.size()>0)
        {
            gly = glies.get(0);
        }
        return gly;
    }

    @Override
    public PageResult findPages(Integer pageNo,Integer pageSize,Gly gly)
    {
        PageHelper.startPage(pageNo,pageSize);

        GlyExample example = new GlyExample();
        GlyExample.Criteria criteria = example.createCriteria();

        if (!ObjectUtils.isEmpty(gly.getGlyUsername()))
        {
            criteria.andGlyUsernameEqualTo(gly.getGlyUsername());
        }
        if (!ObjectUtils.isEmpty(gly.getGlyId()))
        {
            criteria.andGlyIdEqualTo(gly.getGlyId());
        }
        if (!ObjectUtils.isEmpty(gly.getGlyRealname()))
        {
            criteria.andGlyRealnameEqualTo(gly.getGlyRealname());
        }
        if (!ObjectUtils.isEmpty(gly.getGlyPhone()))
        {
            criteria.andGlyPhoneEqualTo(gly.getGlyRealname());
        }

        example.setOrderByClause("gly_username");

        Page<Gly> glyPage = (Page<Gly>)glyMapper.selectByExample(example);

        List<Gly> glyList = glyPage.getResult();

        List<GlyVo> glyVoList = buildGlyVoList(glyList);

        return new PageResult(glyPage.getTotal(),glyVoList);
    }

    private List<GlyVo> buildGlyVoList(List<Gly> glyList)
    {
        List<GlyVo> glyVoList = new ArrayList<>();
        glyList.forEach(gly -> {
            GlyVo glyVo2 = new GlyVo();

            BeanUtils.copyProperties(gly,glyVo2);

            glyVoList.add(glyVo2);
        });

        return glyVoList;
    }
}
